package com.api.sw.duban.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.interfaces.datasource.DataSource;
import weaver.sm.SM4Utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.sql.Date;
import java.sql.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class BaseUtil {

    private final static LogTool loghr = new LogTool("/log/assetlog/luolf/BaseUtil",false);
    private final static LogTool log1 = new LogTool("/log/assetlog/luolf/BaseUtil",false);
    public static String getUserPasswordByRom(String password){
        String newpassword="";
        password= Util.null2String(password).trim();
        newpassword=password;
        if (password.endsWith("_random_")) {
            SM4Utils var50 = new SM4Utils();
            BaseBean var11 = new BaseBean();
            String var12 = Util.null2String(var11.getPropValue("weaver_client_pwd", "key"));
            if (!"".equals(var12)) {
                password = password.substring(0, password.lastIndexOf("_random_"));
                newpassword = var50.decrypt(password, var12);
            }
        }
        return newpassword;
    }

    public static String encrypt(String srcStr, Charset charset, String sKey) {
        byte[] src = srcStr.getBytes(charset);
        byte[] buf = encrypt(src, sKey);
        return parseByte2HexStr(buf);
    }

    public static String decrypt(String hexStr, Charset charset, String sKey) throws Exception {
        byte[] src = parseHexStr2Byte(hexStr);
        byte[] buf = decrypt(src, sKey);
        return new String(buf, charset);
    }

    private static byte[] encrypt(byte[] data, String sKey) {
        try {
            byte[] key = sKey.getBytes();
            IvParameterSpec iv = new IvParameterSpec(key);
            DESKeySpec desKey = new DESKeySpec(key);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);
            return cipher.doFinal(data);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] decrypt(byte[] src, String sKey) throws Exception {
        byte[] key = sKey.getBytes();
        IvParameterSpec iv = new IvParameterSpec(key);
        DESKeySpec desKey = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
        return cipher.doFinal(src);
    }

    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    public static void main1(String[] args) {

        String encryptUserName=encrypt("xiaoh", Charset.forName("UTF-8"), "sloginfr");
        System.out.println("encryptUserName------>"+encryptUserName);
    }
    public static String getFormidId(String workflowid){
        StringBuffer lSQL = new StringBuffer();
        lSQL.append(" SELECT formid FROM workflow_base WHERE id='"+workflowid+"' ");
        RecordSet rs = new RecordSet();
        rs.execute(lSQL.toString());
        String formid="";
        if(rs.next()){
            formid= Util.null2String(rs.getString("formid"));
            formid=Math.abs(Integer.parseInt(formid))+"";
        }
        return formid;
    }
    public static String getFormidIdByrequestid(String requestid){
        StringBuffer lSQL = new StringBuffer();
        lSQL.append(" SELECT a.formid FROM workflow_base a,workflow_requestbase b WHERE b.requestid='"+requestid+"' and a.id=b.workflowid ");
        RecordSet rs = new RecordSet();
        rs.execute(lSQL.toString());
        String formid="";
        if(rs.next()){
            formid= Util.null2String(rs.getString("formid"));
            formid=Math.abs(Integer.parseInt(formid))+"";
        }
        return formid;
    }

    /**
     * 获取流程节点状态ID
     * @param workflowid 流程ID
     * @param type	流程节点类型 0：申请人 1：归档
     * @return  节点ID
     */
    public String getworkflowNode(String workflowid,String type){
        String workflownodeid="";
        if("".equals(Util.null2String(type).trim())){
            type="0";
        }
        RecordSet re=new RecordSet();
        String sql="";
        if("0".equals(Util.null2String(type).trim())){
            sql="select top 100 a.id from workflow_nodebase a,workflow_flownode b where a.id=b.nodeid and  isstart='1' and workflowid='"+workflowid+"'  ";
        }
        if("1".equals(Util.null2String(type).trim())){
            sql="select top 100 a.id from workflow_nodebase a,workflow_flownode b where a.id=b.nodeid and  isend='1' and workflowid='"+workflowid+"'  ";
        }

        re.execute(sql);
        while(re.next()){
            workflownodeid= Util.null2String(re.getString("id")).trim() ;
        }
        return workflownodeid;
    }
    /**
     * 通过映射表定位流程字段对应的取值字段
     *
     * @return  流程取值字段的集合
     */
    public Map<String,String> setFieldMap(){
        Map<String,String> map=new HashMap<String,String>();
        //if("".equals(Util.null2String(field).trim())){
        //return map;
        //}
        String sql="select * from uf_wfmfield";
        RecordSet re=new RecordSet();
        re.execute(sql);
        while(re.next()){
            String workflowfield= Util.null2String(re.getString("wffield")).trim().toLowerCase();
            String modelfield= Util.null2String(re.getString("mfield")).trim().toLowerCase();
            if("".equals(workflowfield)||"".equals(modelfield)){
                continue;
            }
            map.put(workflowfield, modelfield);
        }
        return map;
    }


    public String getWorkflowFieldid(String workflowid,String fieldname){
        if("".equals(Util.null2String(fieldname).trim())){
            return "";
        }
        RecordSet re=new RecordSet();
        String fieldid="";
        String sql="select b.* from  workflow_base a,workflow_billfield b where  "+
                " a.formid=b.billid and a.id='"+workflowid+"' and lower(fieldname)='"+(Util.null2String(fieldname).trim().toLowerCase())+"' ";

        re.execute(sql) ;
        while(re.next()){
            fieldid= Util.null2String(re.getString("id")).trim();
        }
        return fieldid;
    }
    /*
     * 获取字段名称
     */
    public String getWorkflowFieldName(String feildid){
        if("".equals(Util.null2String(feildid).trim())){
            return "";
        }
        RecordSet re=new RecordSet();
        String fieldid="";
        String sql="select   a.*,b.labelname from workflow_billfield a,HtmlLabelInfo b,uf_mwfl c where a.id=c.wffield and a.fieldlabel=b.indexid and b.languageid=7 and c.mfield='"+feildid+"'";

        re.execute(sql) ;
        while(re.next()){
            fieldid= Util.null2String(re.getString("labelname")).trim()+",";
        }
        return fieldid;
    }
    /*
     * 获取下拉框的值
     */
    public String getSelectItemVakName(String feildid,String selectval){
        if("".equals(Util.null2String(feildid).trim())||"".equals(Util.null2String(selectval).trim())){
            return "";
        }
        String selectname="";
        RecordSet re=new RecordSet();
        String sql="select  * from  workflow_SelectItem_model_v where mfield='"+ Util.null2String(feildid).trim()+"' and zsselectvalue in ("+ Util.null2String(selectval).trim()+")   order by listorder";

        re.execute(sql) ;
        while(re.next()){
            selectname= Util.null2String(re.getString("selectname")).trim()+",";
        }
        if(selectname.endsWith(",")){
            selectname=selectname.substring(0,selectname.length()-1);
        }
        return selectname;
    }

    public static boolean executeUpdateTran(String datesource,String sql,Object... params){
        boolean flag=true;
        DataSource ds =null;
        Connection conn = null;
        PreparedStatement stmt =null;
        //获取HR数据源
        try {
            ds = (DataSource) StaticObj.getServiceByFullname(("datasource."+datesource), DataSource.class);
            conn = ds.getConnection();
            stmt = conn.prepareStatement(sql);
            //设置手工提交
            conn.setAutoCommit(false);
            if(params != null && params.length>0) {
                int i = 1;
                for(Object para:params) {
                    if (((para instanceof Integer)) || ((para instanceof Long))){
                        stmt.setInt(i, Util.getIntValue(""+para));
                    }else if ((para instanceof Float)){
                        stmt.setFloat(i, Util.getFloatValue(""+para));
                    }else if (((para instanceof BigDecimal)) || ((para instanceof Double))){
                        if((para instanceof BigDecimal)){
                            stmt.setBigDecimal(i,(BigDecimal)para);
                        }else{
                            double tBig= Util.getDoubleValue(""+para);
                            // BigDecimal temp=new BigDecimal(tBig);
                            stmt.setString(i,doubleToStr(tBig));
                        }
                    }else if ((para instanceof Date)){
                        stmt.setDate(i, (Date)para);
                    }else if (((para instanceof String)) || ((para instanceof Character))){
                        stmt.setString(i, ""+para);
                    }else if (para == null){
                        stmt.setNull(i, 0);
                    }else if ((para instanceof Clob)){
                        stmt.setClob(i, (Clob)para);
                    }else if ((para instanceof Blob)){
                        stmt.setBlob(i, (Blob)para);
                    }else {
                        stmt.setObject(i, para);
                    }
                    i++;
                }
            }
            int len=stmt.executeUpdate();
            if(len>0){
                flag=true;
                conn.commit();
            }else{
                flag=false;
            }
            stmt.close();
        }catch (Exception e){
            try {
                stmt.close();
                conn.close();
            }catch(Exception e1){
                e1.printStackTrace();
            }
            flag=false;
        }
        return flag;
    }
    public static boolean executeUpdateListTran(String datesource, List<Map<String,Object>> list){
        boolean flag=true;
        //获取HR数据源
        RecordSetTrans rest=new RecordSetTrans();

        try {
            rest.setAutoCommit(false);
            for(Map<String,Object> sqls:list) {
                if(sqls==null||sqls.size()<=0){
                    continue;
                }
                String sql=(String)sqls.get("sql");
                log1.writeLog("executeUpdateListTran--->"+sql);
                Object[] params=(Object[])sqls.get("params");
                log1.writeLog("executeUpdateListTran--->"+String.valueOf(params));
                flag=rest.executeUpdate(sql,params);
                if(!flag){
                    throw  new Exception("database final！");
                }
                //int len = stmt.executeUpdate();
                log1.writeLog("len--->"+flag);

            }
            rest.commit();
        }catch (Exception e){
            log1.writeLog("executeUpdateListTranException "+e.getMessage());
            e.printStackTrace();
            try {
                rest.rollback();
            }catch(Exception e1){
                e1.printStackTrace();
            }
            flag=false;
        }
        return flag;
    }

    public static boolean executeUpdateListTranV1(String datesource, List<Map<String,Object>> list){
        boolean flag=true;
        DataSource ds =null;
        Connection conn = null;
        PreparedStatement stmt =null;
        //获取HR数据源
        try {
            ds = (DataSource) StaticObj.getServiceByFullname(("datasource."+datesource), DataSource.class);
            conn = ds.getConnection();
            conn.setAutoCommit(false);
            for(Map<String,Object> sqls:list) {
                if(sqls==null||sqls.size()<=0){
                    continue;
                }
                String sql=(String)sqls.get("sql");
                log1.writeLog("executeUpdateListTran--->"+sql);
                Object[] params=(Object[])sqls.get("params");
                log1.writeLog("executeUpdateListTran--->"+params.length);
                stmt = conn.prepareStatement(sql);
                //设置手工提交

                if (params != null && params.length > 0) {
                    int i = 1;
                    for (Object para : params) {
                        if (((para instanceof Integer)) || ((para instanceof Long))) {
                            stmt.setInt(i, Util.getIntValue("" + para));
                        } else if ((para instanceof Float)) {
                            stmt.setFloat(i, Util.getFloatValue("" + para));
                        } else if (((para instanceof BigDecimal)) || ((para instanceof Double))) {
                            if ((para instanceof BigDecimal)) {
                                stmt.setBigDecimal(i, (BigDecimal) para);
                            } else {
                                double tBig = Util.getDoubleValue("" + para);
                                // BigDecimal temp=new BigDecimal(tBig);
                                if(tBig==0){
                                    stmt.setString(i, null);
                                }else {
                                    stmt.setString(i, doubleToStr(tBig));
                                }
                            }
                        } else if ((para instanceof Date)) {
                            stmt.setDate(i, (Date) para);
                        } else if (((para instanceof String)) || ((para instanceof Character))) {
                            stmt.setString(i, "" + para);
                        } else if (para == null) {
                            stmt.setNull(i, 0);
                        } else if ((para instanceof Clob)) {
                            stmt.setClob(i, (Clob) para);
                        } else if ((para instanceof Blob)) {
                            stmt.setBlob(i, (Blob) para);
                        } else {
                            stmt.setObject(i, para);
                        }
                        i++;
                    }
                }
                int len = stmt.executeUpdate();
                log1.writeLog("len--->"+len);
                if (len >= 0) {
                    flag = true;
                } else {
                    flag = false;
                    stmt.close();
                    conn.rollback();
                    break;
                }
            }
            conn.commit();
            conn.close();
        }catch (Exception e){
            log1.writeLog("executeUpdateListTranException "+e.getMessage());
            e.printStackTrace();
            try {
                conn.rollback();
                conn.close();
            }catch(Exception e1){
                e1.printStackTrace();
            }
            flag=false;
        }
        return flag;
    }

    public static  boolean executeUpdate(String sql,Object... params) throws Exception {
        ConnStatement conn = new ConnStatement();

        try {
            conn.setStatementSql(sql);
            if(params != null && params.length>0) {
                int i = 1;
                for(Object para:params) {
                    if (((para instanceof Integer)) || ((para instanceof Long))){
                        conn.setInt(i, Util.getIntValue(""+para));
                    }else if ((para instanceof Float)){
                        conn.setFloat(i, Util.getFloatValue(""+para));
                    }else if (((para instanceof BigDecimal)) || ((para instanceof Double))){
                        if((para instanceof BigDecimal)){
                            conn.setBigDecimal(i,(BigDecimal)para);
                        }else{
                            double tBig= Util.getDoubleValue(""+para);
                            // BigDecimal temp=new BigDecimal(tBig);
                            conn.setString(i,doubleToStr(tBig));
                        }
                    }else if ((para instanceof Date)){
                        conn.setDate(i, (Date)para);
                    }else if (((para instanceof String)) || ((para instanceof Character))){
                        conn.setString(i, ""+para);
                    }else if (para == null){
                        conn.setNull(i, 0);
                    }else if ((para instanceof Clob)){
                        conn.setClob(i, (Clob)para);
                    }else if ((para instanceof Blob)){
                        conn.setBlob(i, (Blob)para);
                    }else {
                        conn.setObject(i, para);
                    }
                    i++;
                }
            }
            conn.executeUpdate();

        }catch(Exception e){
            //printLog(sql,params);
            throw e;
        }finally {
            conn.close();
        }
        return true;
    }
    /**
     * 转换URL的中文
     * @param url
     * @return
     * @throws UnsupportedEncodingException
     */
    private String convertURL(String url,String code) throws UnsupportedEncodingException {
        String urlStr = "";
        //将中文分割出来 以UTF8编码
        String strs[] = url.split("/");
        if(strs.length==0) urlStr = url;
        int i = 0;
        for(String s : strs){
            if(i == (strs.length-1)){
                if(isChinese(s)){
                    urlStr += URLEncoder.encode(s, code)+"";
                }else{
                    urlStr += s+"";
                }
            }else{
                if(isChinese(s)){
                    urlStr += URLEncoder.encode(s, code)+"/";
                }else{
                    urlStr += s+"/";
                }
            }
            i++;
        }
        return urlStr;
    }
    /**
     * 判断是否包含中文字符
     * @param strName
     * @return
     */
    boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c) == true) {
                return isChinese(c);
            } else {
                if(i == (ch.length-1)){
                    return isChinese(c);
                }else{
                    continue;
                }
            }
        }
        return false;
    }
    boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
    public static String getTempFilename(String str){
        String tempName="";
        try{
            if(str==null||"".equals(str)){
                return "";
            }
            if(str.indexOf("?")>1){
                str=str.substring(0,str.indexOf("?"));
            }
            tempName=str.substring(str.lastIndexOf("/")+1);
        }catch(Exception e){

        }
        return tempName;
    }
    /**
     * java dobule数据转字符串输出
     * @param tempX 需要被转换的数据
     * @return 默认保留4位小数输出
     */
    public static String doubleToStr(double tempX) {
        double newStemp=round(tempX, 4);
        DecimalFormat df = new DecimalFormat("0.0000");
        String newff = df.format(newStemp);
        return newff;
    }
    /**
     * 四舍五入
     * @param v
     * @param scale 精确位数
     */
    public static double round(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    /**
     * 四舍五入
     * @param v
     * @param scale 精确位数
     */
    public static float roundF(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).floatValue();
    }
    /*
    拼接文号
     */
    public static String getWh(int len){
        if(len<=0){
            return "";
        }
        String str="";
        for(int i=0;i<len;i++){
            str=str+"?,";
        }
        if(str.endsWith(",")){
            str=str.substring(0,str.length()-1);
        }
        return str;
    }
    //过滤HTML
    public static String Html2Text(String inputString) {
        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        Pattern p_script;
        java.util.regex.Matcher m_script;
        Pattern p_style;
        java.util.regex.Matcher m_style;
        Pattern p_html;
        java.util.regex.Matcher m_html;

        Pattern p_html1;
        java.util.regex.Matcher m_html1;

        try {
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
            // }
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
            // }
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
            String regEx_html1 = "<[^>]+";
            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签

            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签

            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签

            p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
            m_html1 = p_html1.matcher(htmlStr);
            htmlStr = m_html1.replaceAll(""); // 过滤html标签

            textStr = htmlStr;

        } catch (Exception e) {
            //System.err.println("Html2Text: " + e.getMessage());
            textStr="";
        }

        return textStr;// 返回文本字符串
    }
    /*
    获取字段ID
     */
    public static String getFilebillid(String feildname,int bilid,int dettail){
        String fieldid="";
        RecordSet re=new RecordSet();
        String sql="";
        if(dettail<=0){//主表
            sql="select * from workflow_billfield where upper(fieldname)=upper('"+feildname+"') and billid=-"+bilid;
        }else{//明细
            sql="select * from workflow_billfield where upper(fieldname)=upper('"+feildname+"') and detailtable='formtable_main_"+bilid+"_dt"+dettail+"' and billid=-"+bilid;
        }
        loghr.writeLog("getFilebillid---"+sql);
        re.execute(sql);
        while(re.next()){
            fieldid= Util.null2String(re.getString("id")).trim();
        }
        return fieldid;
    }
    /*
    获取主流程的 requestid  以及requestmark
     */
    public static Map<String,String> getMainRequestbaseByreq(String requestid){
        Map<String,String> main=new HashMap<>();
        RecordSet re=new RecordSet();
        String mainrequestid="";
        String mainrequestmark="";
        String sql="select b.requestid,b.requestmark from workflow_requestbase a left join workflow_requestbase b on a.mainrequestid=b.requestid where a.requestid='"+requestid+"' ";
        log1.writeLog("getMainRequestbaseByreq--"+sql);
        re.execute(sql);
        while(re.next()){
              mainrequestid= Util.null2String(re.getString("requestid")).trim() ;
              mainrequestmark= Util.null2String(re.getString("requestmark")).trim() ;
        }
        main.put("mainrequestid",mainrequestid);
        main.put("mainrequestmark",mainrequestmark);
        log1.writeLog("getMainRequestbaseByreq--"+main.toString());
        return main;
    }
    public static double getfloats(String demo,int len){
        //Logger log = Logger.getLogger(BigDecimal.class);
        if(len==0){
            len=2;
        }
        String str= Util.null2String(demo);
        if("".equals(str)||"".equals(str.trim())||"null".equalsIgnoreCase(str.trim())){
            return 0;
        }
        double fl=0.0f;
        //String str=Util.null2String(demo);
        try{
            if(str.trim().length()>0){
                BigDecimal b1 = new BigDecimal(str.trim());
                //System.out.println(b1.setScale(2,BigDecimal.ROUND_HALF_UP));
                fl=b1.setScale(len,BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            //log.error("getfloats"+fl);
        }catch(Exception e){
            loghr.writeLog(demo+"getfloats异常"+e.getMessage());
        }

        return fl;
    }
    /*
    设置跟新的 数据的 标准的   数据  只是更新 一二级 分解  其他的不动
     */
    public static List<Map<String, Object>> BaseUpdDate(String requestid){
        RecordSet re=new RecordSet();
        List<Map<String, Object>> listMap=new ArrayList<Map<String, Object>>();
        Map<String, Object> map = null;//new HashMap<String, Object>();
        String sql="select * from  uf_zjljlhzbb where mainrequestid='"+requestid+"' and  isnull(jb,-1) in (1,2) and isnull(sfyx,-1) in (0,-1)";
        re.execute(sql);
        while(re.next()){
            String id= Util.null2String( re.getString("id")).trim();
            if(!"".equals(id)){
                //设置更新数据  建模
                Object[] objval = new Object[1];//存储值
                objval[0]=id;
                map=new HashMap<String, Object>();
                map.put("sql","update uf_zjljlhzbb set sfyx='1' where id=?");
                map.put("params",objval);
                listMap.add(map);
            }
        }
        return listMap;
    }
    // 通过 主流程 获取 以及分解 流程requestid  以及 requestmark
    public static Map<String,String> getReqMarkByMainreq(String mainrequestid){
        RecordSet re=new RecordSet();
        Map<String,String> map=new HashMap<String,String>();
        //取一级分解
        String sql="select * from uf_zjljlhzbb where tragwfreq='"+mainrequestid+"' and isnull(jb,-1)=1 and isnull(sfyx,-1) in (0,-1)";
        re.execute(sql);
        if(re.next()){
            String requestid= Util.null2String(re.getString("wfrequestid"));
            String requestmark= Util.null2String(re.getString("wfrequestmark"));
            map.put("requestid",requestid);
            map.put("requestmark",requestmark);
        }
        return map;
    }
    //获取分部矩阵信息
    public static String getMax_1(String userid,String subid){
        String subidStr="";
        RecordSet re=new RecordSet();
        String sql="select * from matrixtable_1 where ','+CAST(jxsjxgy as varchar(800))+','  like ',"+userid+",' and id in ("+subid+")";
        log1.writeLog("getMax_1--->"+sql);
        re.execute(sql);
        while(re.next()){
            String id= Util.null2String(re.getString("id")).trim() ;
            if("".equals(id)){
                continue;
            }
            subidStr=subidStr+id+",";
        }
        if(subidStr.endsWith(",")){
            subidStr=subidStr.substring(0,subidStr.length()-1);
        }
        return subidStr;
    }
    //通过部门以及人员获取分部矩阵信息
    public static String getMax_1ByDep(String userid,String depid){
        String subidStr="";
        RecordSet re=new RecordSet();
        String sql="select * from matrixtable_1 where ','+CAST(jxsjxgy as varchar(800))+','  like ',"+userid+",' and id in (select subcompanyid1 from hrmdepartment where id in ("+depid+"))";
        log1.writeLog("getMax_1ByDep--->"+sql);
        re.execute(sql);
        while(re.next()){
            String id= Util.null2String(re.getString("id")).trim() ;
            if("".equals(id)){
                continue;
            }
            subidStr=subidStr+id+",";
        }
        if(subidStr.endsWith(",")){
            subidStr=subidStr.substring(0,subidStr.length()-1);
        }
        return subidStr;
    }
    //通过部门以及人员获取分部矩阵信息
    public static JSONObject getMax_2ByUser(String userid, String depid){
        JSONObject json=new JSONObject();
        String subidStr="";
        String depidStr="";
        RecordSet re=new RecordSet();
        String sql="select a.id,b.subcompanyid1 from matrixtable_2 a , HrmDepartment b   where a.id=b.id and  ','+CAST(a.bc as varchar(800))+','  like ',"+userid+",' and a.id in ("+depid+") ";
        log1.writeLog("getMax_2ByUser--->"+sql);
        re.execute(sql);
        while(re.next()){
            String id= Util.null2String(re.getString("id")).trim() ;
            String subcompanyid1= Util.null2String(re.getString("subcompanyid1")).trim() ;
            if("".equals(id)){
                continue;
            }
            subidStr=subidStr+subcompanyid1+",";
            depidStr=depidStr+id+",";
        }
        if(depidStr.endsWith(",")){
            depidStr=depidStr.substring(0,depidStr.length()-1);
        }
        if(subidStr.endsWith(",")){
            subidStr=subidStr.substring(0,subidStr.length()-1);
        }
        json.put("dep",depidStr);
        json.put("sub",subidStr);
        return json;
    }
    /*
        获取单位分部数据
        添加判断还未设置完成的 不允许变更  或者有变更数据没有归档

        校验是否存在 分部 没分解  部门分解数据等

        sudid  分部id
        mainRequestid 主数据ID
        0:总经理分解
        1:一级分解
        2:二级分解
     */
    public static JSONObject getSubData(String sudid, String mainRequestid, String requestid){
        RecordSet re=new RecordSet();
        JSONObject resultjson=new JSONObject();
        JSONObject json=new JSONObject();
        JSONArray jsons=new JSONArray();

        JSONObject levezjl=new JSONObject();//总经理

        JSONObject leve1_dw=new JSONObject();//一级 单位
        JSONObject leve1_gr=new JSONObject();//一级  个人
        JSONObject leve1_dp=new JSONObject();//一级  大盘


        JSONObject leve2=new JSONObject();//二级

        JSONObject fblxje=new JSONObject();//单位分解大盘金额
        JSONObject fblx=new JSONObject();//单位分解类型
        JSONObject bmlxje=new JSONObject();//单位分解大盘金额
        //不可存在在途变更流程 会造成数据混轮乱
        if(checkChangeWf(mainRequestid,requestid)){
            return resultjson;
        }
        String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " +
                   " left join hrmdepartment c on a.jldwbm=c.id  " +
                   " left join hrmresource d on  a.xm=d.id " +
                   " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+")";
        log1.writeLog("getSubDatanew--->"+sql);

        re.execute(sql);
        while(re.next()){
            json=new JSONObject();
            String id= Util.null2String(re.getString("id")).trim();//建模ID
            String jb= Util.null2String(re.getString("jb")).trim();//级别
            if("".equals(jb)){
                continue;
            }

            String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额
            String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额
            String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型
            String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位（分部）
            String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额（分部）
            String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额
            String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额
            String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注
            String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导
            String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额
            String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注
            String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位（部门）
            String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额（部门）
            String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注
            String xm= Util.null2String(re.getString("xm")).trim();//姓名
            String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额
            String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注
            String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额（部门）
            String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称
            String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称
            String lastname= Util.null2String(re.getString("lastname")).trim();//姓名
            String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid
            String wfrequestid= Util.null2String(re.getString("wfrequestid")).trim();//mainrequestid
            if("0".equals(jb)){

                if("1".equals(levezjl.getString(bjldwfb))){
                        continue;
                }
                levezjl.put(bjldwfb,"1");
            }
            if("1".equals(jb)){
                fblxje.put(bjldwfb,hrfbdpje);
                fblx.put(bjldwfb,fjlx);
                if("0".equals(fjlx)){//单位
                    //leve1_dw.put(bjldwfb,jldwbm);
                    if("".equals(Util.null2String(leve1_dw.getString(bjldwfb)).trim())){
                        leve1_dw.put(bjldwfb,jldwbm+",");
                    }else{
                        String bmstr= Util.null2String(leve1_dw.getString(bjldwfb)).trim();
                        bmstr=bmstr+jldwbm+",";
                        leve1_dw.put(bjldwfb,bmstr);
                    }
                }
                if("1".equals(fjlx)){//个人
                    leve1_gr.put(bjldwfb,"1");
                }
                if("2".equals(fjlx)){//大盘
                    leve1_dp.put(bjldwfb,"1");
                }
            }
            if("2".equals(jb)){
                leve2.put(jldwbm,"1");
                bmlxje.put(jldwbm,hrdpjebm );
            }
            JSONArray demoJsons=resultjson.getJSONArray(jb);
            if(demoJsons==null||demoJsons.size()<=0){
                demoJsons=new JSONArray();
                resultjson.put(jb,demoJsons);
            }
            json.put("jb",jb);
            json.put("id",id);
            json.put("sqjlje",sqjlje);
            json.put("hrfbdpje",hrfbdpje);
            json.put("fjlx",fjlx);
            json.put("bjldwfb",bjldwfb);
            json.put("jljefb",jljefb);
            json.put("qzzcldjlje",qzzcldjlje);
            json.put("qzjldwje",qzjldwje);
            json.put("jlfpbz",jlfpbz);
            json.put("zcld",zcld);
            json.put("zcldjlje",zcldjlje);
            json.put("zcldfpbz",zcldfpbz);
            json.put("jldwbm",jldwbm);
            json.put("dwjljebm",dwjljebm);
            json.put("dwjlbz",dwjlbz);
            json.put("xm",xm);
            json.put("grjlje",grjlje);
            json.put("grjlbz",grjlbz);
            json.put("hrdpjebm",hrdpjebm);
            json.put("subcompanyname",subcompanyname);
            json.put("departmentname",departmentname);
            json.put("lastname",lastname);
            json.put("mainrequestid",mainrequestid);
            json.put("wfrequestid",wfrequestid);
            demoJsons.add(json);

        }
        log1.writeLog(resultjson.toJSONString());
        log1.writeLog(levezjl.toJSONString());
        log1.writeLog(leve1_dw.toJSONString());
        log1.writeLog(leve1_gr.toJSONString());
        log1.writeLog(leve1_dp.toJSONString());
        log1.writeLog(leve2.toJSONString());
        log1.writeLog(fblxje.toJSONString());
        log1.writeLog(fblx.toJSONString());
        //检验数据
        if(levezjl.size()>0){
            Set<String> fbkey= levezjl.keySet();
            for(String key:fbkey){
                String str1= Util.null2String(leve1_dw.getString(key)).trim() ;
                String str2= Util.null2String(leve1_gr.getString(key)).trim() ;
                String str3= Util.null2String(leve1_dp.getString(key)).trim() ;
                if("".equals(str1)&&"".equals(str2)&&"".equals(str3)){

                    log1.writeLog("not sub data"+key);
                    return new JSONObject();
                }
                if(!"".equals(str1)){
                   String[] bmAll= str1.split(",");
                   for(String str:bmAll){

                        if(!"".equals(str)){
                            if(!"1".equals(Util.null2String(leve2.getString(str)).trim())){
                                log1.writeLog("not dep data"+str);
                                return new JSONObject();
                            }
                        }
                   }
                }
            }

        }else{
            return new JSONObject();
        }
        if(resultjson.size()>0){
            resultjson.put("fbje",fblxje);
            resultjson.put("fblx",fblx);
            resultjson.put("bmje",bmlxje);
        }
        return resultjson;
    }
    /*
        获取单位部门数据(用于只是修改二级分解个人数据)
        sudid  分部id
        mainRequestid 主数据ID
        0:总经理分解
        1:一级分解
        2:二级分解
     */
    public static JSONObject getDepData(String depid, String sudid, String mainRequestid){
        RecordSet re=new RecordSet();
        JSONObject resultjson=new JSONObject();
        JSONObject json=new JSONObject();
        JSONObject bmdpJson=new JSONObject();

        JSONObject bmTofb=new JSONObject();//部门所属分部
        JSONObject userTobm=new JSONObject();//人员所属部门

        JSONArray jsons=new JSONArray();
        JSONObject levezjl=new JSONObject();
        String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " +
                " left join hrmdepartment c on a.jldwbm=c.id  " +
                " left join hrmresource d on  a.xm=d.id " +
                " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and isnull(jb,-1)=0"+
                " union all "+
                "select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " +
                " left join hrmdepartment c on a.jldwbm=c.id  " +
                " left join hrmresource d on  a.xm=d.id " +
                " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and a.jldwbm in ("+depid+") and isnull(jb,-1)=1 and fjlx='0' "+
                " union all "+
                " select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " +
                " left join hrmdepartment c on a.jldwbm=c.id  " +
                " left join hrmresource d on  a.xm=d.id " +
                " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and a.jldwbm in ("+depid+") and isnull(jb,-1)=2";
        log1.writeLog("getDepData--->"+sql);
        re.execute(sql);
        while(re.next()){
            json=new JSONObject();
            String id= Util.null2String(re.getString("id")).trim();//建模ID
            String jb= Util.null2String(re.getString("jb")).trim();//级别
            if("".equals(jb)){
                continue;
            }
            String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额
            String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额
            String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型
            String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位（分部）
            String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额（分部）
            String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额
            String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额
            String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注
            String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导
            String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额
            String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注
            String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位（部门）
            String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额（部门）
            String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注
            String xm= Util.null2String(re.getString("xm")).trim();//姓名
            String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额
            String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注
            String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额（部门）
            String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称
            String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称
            String lastname= Util.null2String(re.getString("lastname")).trim();//姓名
            String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid
            if("".equals(bjldwfb)||"".equals(jldwbm)){
                continue;
            }
            if("0".equals(jb)){
                if("1".equals(levezjl.getString(bjldwfb))){
                    continue;
                }
                levezjl.put(bjldwfb,"1");
            }
            if("1".equals(jb)){//一级分解
                bmTofb.put(jldwbm,bjldwfb);
            }

            JSONArray demoJsons=resultjson.getJSONArray(jb);
            if(demoJsons==null||demoJsons.size()<=0){
                demoJsons=new JSONArray();
                resultjson.put(jb,demoJsons);
            }
            if("2".equals(jb)){
                bmdpJson.put(jldwbm,hrdpjebm);
                userTobm.put(jldwbm,"1");
            }
            json.put("jb",jb);
            json.put("id",id);
            json.put("sqjlje",sqjlje);
            json.put("hrfbdpje",hrfbdpje);
            json.put("fjlx",fjlx);
            json.put("bjldwfb",bjldwfb);
            json.put("jljefb",jljefb);
            json.put("qzzcldjlje",qzzcldjlje);
            json.put("qzjldwje",qzjldwje);
            json.put("jlfpbz",jlfpbz);
            json.put("zcld",zcld);
            json.put("zcldjlje",zcldjlje);
            json.put("zcldfpbz",zcldfpbz);
            json.put("jldwbm",jldwbm);
            json.put("dwjljebm",dwjljebm);
            json.put("dwjlbz",dwjlbz);
            json.put("xm",xm);
            json.put("grjlje",grjlje);
            json.put("grjlbz",grjlbz);
            json.put("hrdpjebm",hrdpjebm);
            json.put("subcompanyname",subcompanyname);
            json.put("departmentname",departmentname);
            json.put("lastname",lastname);
            json.put("mainrequestid",mainrequestid);
            demoJsons.add(json);

        }
        //校验数据是否分解完毕
        //int fblen=0;//分部计数
        log1.writeLog(" levezjl-->"+levezjl.toJSONString());
        log1.writeLog(" bmTofb-->"+bmTofb.toJSONString());
        log1.writeLog(" userTobm-->"+userTobm.toJSONString());
        JSONObject fblen=new JSONObject();//分部计数
        if(levezjl.size()>0){
            //Set<String> levezjlkey=levezjl.keySet();
            //for(String key:levezjlkey){

            //}

            if(bmTofb.size()>0){
                Set<String> bmTofbkey=bmTofb.keySet();
                for(String key:bmTofbkey){//key 代表分部
                    String fbkey=bmTofb.getString(key);
                    String userTobmStr= Util.null2String(userTobm.getString(key)).trim() ;
                    if(!"1".equals(userTobmStr)){
                        return new JSONObject();
                    }else{
                        fblen.put(fbkey,"-1");
                    }
                }
                if(fblen.size()!=levezjl.size()){
                    return new JSONObject();
                }
            }else{
                return new JSONObject();
            }

        }else{
            return new JSONObject();
        }
        if(resultjson.size()>0){
            resultjson.put("bmdp",bmdpJson);
        }

        log1.writeLog(resultjson.toJSONString());

        return resultjson;
    }
    /*
       获取单位部门数据(用于只是修改二级分解个人数据)
       sudid  分部id
       mainRequestid 主数据ID
       0:总经理分解
       1:一级分解
       2:二级分解
    */
    public static JSONObject getDepDataDetail(String depid, String sudid, String mainRequestid){
        RecordSet re=new RecordSet();
        boolean leve2l=false;//是否存在二级分部
        JSONObject resultjson=new JSONObject();
        JSONObject DetailJson=new JSONObject();
        JSONObject json=new JSONObject();
        JSONArray jsons=new JSONArray();
        String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " +
                " left join hrmdepartment c on a.jldwbm=c.id  " +
                " left join hrmresource d on  a.xm=d.id " +
                " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and isnull(jb,-1)=0"+
                " union all "+
                "select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " +
                " left join hrmdepartment c on a.jldwbm=c.id  " +
                " left join hrmresource d on  a.xm=d.id " +
                " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and a.jldwbm in ("+depid+") and isnull(jb,-1)=1 and fjlx='0' "+
                " union all "+
                " select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " +
                " left join hrmdepartment c on a.jldwbm=c.id  " +
                " left join hrmresource d on  a.xm=d.id " +
                " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+") and a.jldwbm in ("+depid+") and isnull(jb,-1)=2";
        log1.writeLog("getDepDataDetail--->"+sql);
        re.execute(sql);
        while(re.next()){
            json=new JSONObject();
            String id= Util.null2String(re.getString("id")).trim();//建模ID
            String jb= Util.null2String(re.getString("jb")).trim();//级别
            if("".equals(jb)){
                continue;
            }
            if("2".equals(jb)){//存在部门分解
                leve2l=true;
            }
            if("0".equals(jb)||"2".equals(jb)){
                continue;
            }

            String nf= Util.null2String(re.getString("nf")).trim();//年份
            String yf= Util.null2String(re.getString("yf")).trim();//月份
            String sqr= Util.null2String(re.getString("sqr")).trim();//申请人
            String jlxmmc= Util.null2String(re.getString("jlxmmc")).trim();//奖励项目名称

            String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额
            String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额
            String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型
            String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位（分部）
            String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额（分部）
            String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额
            String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额
            String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注
            String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导
            String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额
            String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注
            String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位（部门）
            String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额（部门）
            String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注
            String xm= Util.null2String(re.getString("xm")).trim();//姓名
            String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额
            String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注
            String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额（部门）
            String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称
            String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称
            String lastname= Util.null2String(re.getString("lastname")).trim();//姓名
            String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid

            String ndjhxm= Util.null2String(re.getString("ndjhxm")).trim();//年度计划-项目
            String ndjhys= Util.null2String(re.getString("ndjhys")).trim();//年度计划-预算
            String ndjhsyed= Util.null2String(re.getString("ndjhsyed")).trim();//年度计划-剩余额度
            String qzjldwjezj= Util.null2String(re.getString("qzjldwjezj")).trim();//其中奖励单位金额总计
            String zcldjljehj= Util.null2String(re.getString("zcldjljehj")).trim();//中层领导奖励金额合计
            String wfrequestid= Util.null2String(re.getString("wfrequestid")).trim();//mainrequestid
            json.put("jlxmmc",jlxmmc);
            json.put("nf",nf);
            json.put("yf",yf);
            json.put("sqr",sqr);
            json.put("jb",jb);
            json.put("id",id);
            json.put("sqjlje",sqjlje);
            json.put("hrfbdpje",hrfbdpje);
            json.put("fjlx",fjlx);
            json.put("bjldwfb",bjldwfb);
            json.put("jljefb",jljefb);
            json.put("qzzcldjlje",qzzcldjlje);
            json.put("qzjldwje",qzjldwje);
            json.put("jlfpbz",jlfpbz);
            json.put("zcld",zcld);
            json.put("zcldjlje",zcldjlje);
            json.put("zcldfpbz",zcldfpbz);
            json.put("jldwbm",jldwbm);
            json.put("dwjljebm",dwjljebm);
            json.put("dwjlbz",dwjlbz);
            json.put("xm",xm);
            json.put("grjlje",grjlje);
            json.put("grjlbz",grjlbz);
            json.put("hrdpjebm",hrdpjebm);
            json.put("subcompanyname",subcompanyname);
            json.put("departmentname",departmentname);
            json.put("lastname",lastname);
            json.put("mainrequestid",mainrequestid);

            json.put("ndjhxm",ndjhxm);
            json.put("ndjhys",ndjhys);
            json.put("ndjhsyed",ndjhsyed);
            json.put("qzjldwjezj",qzjldwjezj);
            json.put("zcldjljehj",zcldjljehj);
            json.put("wfrequestid",wfrequestid);
            if("1".equals(jb)){

                if(DetailJson.get(jldwbm)!=null){
                    log1.writeLog("dep must only!");
                    return new JSONObject();
                }
                DetailJson.put(jldwbm,json);
            }
            //demoJsons.add(json);

        }
        log1.writeLog(DetailJson.toJSONString());
        //resultjson.put("DetailJson",DetailJson);
        return DetailJson;
    }
    /*
       获取单位分部数据  按部门区分
       sudid  分部id
       mainRequestid 主数据ID
       0:总经理分解
       1:一级分解
       2:二级分解
       返回  数据集合 以及  ID集合
    */
    public static JSONObject getSubDataDetail(String sudid, String mainRequestid){
        RecordSet re=new RecordSet();
        JSONObject DetailJson=new JSONObject();
        JSONObject Depjson=new JSONObject();
        JSONObject resultjson=null;//new JSONObject();
        JSONObject json=new JSONObject();
        JSONArray jsons=new JSONArray();
        String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " +
                " left join hrmdepartment c on a.jldwbm=c.id  " +
                " left join hrmresource d on  a.xm=d.id " +
                " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+")";
        log1.writeLog("getSubData--->"+sql);
        re.execute(sql);
        while(re.next()){
            json=new JSONObject();
            String jlxmmc= Util.null2String(re.getString("jlxmmc")).trim();//名称
            String sqr= Util.null2String(re.getString("sqr")).trim();//申请人
            String id= Util.null2String(re.getString("id")).trim();//建模ID
            String jb= Util.null2String(re.getString("jb")).trim();//级别
            String nf= Util.null2String(re.getString("nf")).trim();//年份
            String yf= Util.null2String(re.getString("yf")).trim();//月份
            String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额
            String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额
            String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型
            String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位（分部）
            String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额（分部）
            String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额
            String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额
            String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注
            String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导
            String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额
            String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注
            String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位（部门）
            String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额（部门）
            String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注
            String xm= Util.null2String(re.getString("xm")).trim();//姓名
            String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额
            String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注
            String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额（部门）
            String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称
            String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称
            String lastname= Util.null2String(re.getString("lastname")).trim();//姓名
            String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid
            String wfrequestid= Util.null2String(re.getString("wfrequestid")).trim();//wfrequestid

            String ndjhxm= Util.null2String(re.getString("ndjhxm")).trim();//年度计划-项目
            String ndjhys= Util.null2String(re.getString("ndjhys")).trim();//年度计划-预算
            String ndjhsyed= Util.null2String(re.getString("ndjhsyed")).trim();//年度计划-剩余额度
            String qzjldwjezj= Util.null2String(re.getString("qzjldwjezj")).trim();//其中奖励单位金额总计
            String zcldjljehj= Util.null2String(re.getString("zcldjljehj")).trim();//中层领导奖励金额合计


            if("".equals(jb)||"".equals(bjldwfb)){
                continue;
            }
            //DetailJson
            resultjson= Depjson.getJSONObject(bjldwfb);
            if(resultjson==null||resultjson.size()<=0){
                resultjson=new JSONObject();
                Depjson.put(bjldwfb,resultjson);
            }

            JSONArray ModelJson=resultjson.getJSONArray(jb);
            if(ModelJson==null||ModelJson.size()<=0){
                ModelJson=new JSONArray();
                resultjson.put(jb,ModelJson);
            }
            json.put("jlxmmc",jlxmmc);
            json.put("sqr",sqr);
            json.put("jb",jb);
            json.put("id",id);
            json.put("nf",nf);
            json.put("yf",yf);
            json.put("sqjlje",sqjlje);
            json.put("hrfbdpje",hrfbdpje);
            json.put("fjlx",fjlx);
            json.put("bjldwfb",bjldwfb);
            json.put("jljefb",jljefb);
            json.put("qzzcldjlje",qzzcldjlje);
            json.put("qzjldwje",qzjldwje);
            json.put("jlfpbz",jlfpbz);
            json.put("zcld",zcld);
            json.put("zcldjlje",zcldjlje);
            json.put("zcldfpbz",zcldfpbz);
            json.put("jldwbm",jldwbm);
            json.put("dwjljebm",dwjljebm);
            json.put("dwjlbz",dwjlbz);
            json.put("xm",xm);
            json.put("grjlje",grjlje);
            json.put("grjlbz",grjlbz);
            json.put("hrdpjebm",hrdpjebm);
            json.put("subcompanyname",subcompanyname);
            json.put("departmentname",departmentname);
            json.put("lastname",lastname);
            json.put("mainrequestid",mainrequestid);
            json.put("wfrequestid",wfrequestid);

            json.put("ndjhxm",ndjhxm);
            json.put("ndjhys",ndjhys);
            json.put("ndjhsyed",ndjhsyed);
            json.put("qzjldwjezj",qzjldwjezj);
            json.put("zcldjljehj",zcldjljehj);
            ModelJson.add(json);
            DetailJson.put(id,copyJson(json));

        }
        log1.writeLog(Depjson.toJSONString());
        Depjson.put("DetailJson",DetailJson);
        return Depjson;
    }
    /*
        获取单位分部数据  按部门区分
        sudid  分部id
        mainRequestid 主数据ID
        0:总经理分解
        1:一级分解
        2:二级分解
        返回  数据集合 以及  ID集合
     */
    public static JSONObject getSubDataDetailJson(String sudid, String mainRequestid){
        RecordSet re=new RecordSet();
        JSONObject DetailJson=new JSONObject();
        JSONObject Depjson=new JSONObject();
        JSONObject resultjson=null;//new JSONObject();
        JSONObject json=new JSONObject();
        JSONArray jsons=new JSONArray();
        String sql="select a.*,b.subcompanyname,c.departmentname,d.lastname from uf_zjljlhzbb a left join HrmSubCompany b on a.bjldwfb=b.id " +
                " left join hrmdepartment c on a.jldwbm=c.id  " +
                " left join hrmresource d on  a.xm=d.id " +
                " where mainrequestid='"+mainRequestid+"' and isnull(sfyx,-1) in (0,-1) and a.bjldwfb in ("+sudid+")";
        log1.writeLog("getSubData--->"+sql);
        re.execute(sql);
        while(re.next()){
            json=new JSONObject();
            String sqr= Util.null2String(re.getString("sqr")).trim();//申请人
            String id= Util.null2String(re.getString("id")).trim();//建模ID
            String jb= Util.null2String(re.getString("jb")).trim();//级别
            String nf= Util.null2String(re.getString("nf")).trim();//年份
            String yf= Util.null2String(re.getString("yf")).trim();//月份
            String sqjlje= Util.null2String(re.getString("sqjlje")).trim();//申请奖励金额
            String hrfbdpje= Util.null2String(re.getString("hrfbdpje")).trim();//划入分部大盘金额
            String fjlx= Util.null2String(re.getString("fjlx")).trim();//分解类型
            String bjldwfb= Util.null2String(re.getString("bjldwfb")).trim();//被奖励单位（分部）
            String jljefb= Util.null2String(re.getString("jljefb")).trim();//奖励金额（分部）
            String qzzcldjlje= Util.null2String(re.getString("qzzcldjlje")).trim();//其中中层领导奖励金额
            String qzjldwje= Util.null2String(re.getString("qzjldwje")).trim();//其中奖励单位金额
            String jlfpbz= Util.null2String(re.getString("jlfpbz")).trim();//奖励分配备注
            String zcld= Util.null2String(re.getString("zcld")).trim();//中层领导
            String zcldjlje= Util.null2String(re.getString("zcldjlje")).trim();//中层领导奖励金额
            String zcldfpbz= Util.null2String(re.getString("zcldfpbz")).trim();//中层领导分配备注
            String jldwbm= Util.null2String(re.getString("jldwbm")).trim();//奖励单位（部门）
            String dwjljebm= Util.null2String(re.getString("dwjljebm")).trim();//单位奖励金额（部门）
            String dwjlbz= Util.null2String(re.getString("dwjlbz")).trim();//单位奖励备注
            String xm= Util.null2String(re.getString("xm")).trim();//姓名
            String grjlje= Util.null2String(re.getString("grjlje")).trim();//个人奖励金额
            String grjlbz= Util.null2String(re.getString("grjlbz")).trim();//个人奖励备注
            String hrdpjebm= Util.null2String(re.getString("hrdpjebm")).trim();//划入大盘金额（部门）
            String subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();//分部名称
            String departmentname= Util.null2String(re.getString("departmentname")).trim();//部门名称
            String lastname= Util.null2String(re.getString("lastname")).trim();//姓名
            String mainrequestid= Util.null2String(re.getString("mainrequestid")).trim();//mainrequestid
            String wfrequestid= Util.null2String(re.getString("wfrequestid")).trim();//wfrequestid

            String ndjhxm= Util.null2String(re.getString("ndjhxm")).trim();//年度计划-项目
            String ndjhys= Util.null2String(re.getString("ndjhys")).trim();//年度计划-预算
            String ndjhsyed= Util.null2String(re.getString("ndjhsyed")).trim();//年度计划-剩余额度
            String qzjldwjezj= Util.null2String(re.getString("qzjldwjezj")).trim();//其中奖励单位金额总计
            String zcldjljehj= Util.null2String(re.getString("zcldjljehj")).trim();//中层领导奖励金额合计

            if("".equals(jb)||"".equals(bjldwfb)){
                continue;
            }
            //DetailJson
            resultjson= Depjson.getJSONObject(bjldwfb);
            if(resultjson==null||resultjson.size()<=0){
                resultjson=new JSONObject();
                Depjson.put(bjldwfb,resultjson);
            }

            JSONObject ModelJson=resultjson.getJSONObject(jb);

            if(ModelJson==null||ModelJson.size()<=0){
                ModelJson=new JSONObject();
                resultjson.put(jb,ModelJson);
            }
            json.put("sqr",sqr);
            json.put("jb",jb);
            json.put("id",id);
            json.put("nf",nf);
            json.put("yf",yf);
            json.put("sqjlje",sqjlje);
            json.put("hrfbdpje",hrfbdpje);
            json.put("fjlx",fjlx);
            json.put("bjldwfb",bjldwfb);
            json.put("jljefb",jljefb);
            json.put("qzzcldjlje",qzzcldjlje);
            json.put("qzjldwje",qzjldwje);
            json.put("jlfpbz",jlfpbz);
            json.put("zcld",zcld);
            json.put("zcldjlje",zcldjlje);
            json.put("zcldfpbz",zcldfpbz);
            json.put("jldwbm",jldwbm);
            json.put("dwjljebm",dwjljebm);
            json.put("dwjlbz",dwjlbz);
            json.put("xm",xm);
            json.put("grjlje",grjlje);
            json.put("grjlbz",grjlbz);
            json.put("hrdpjebm",hrdpjebm);
            json.put("subcompanyname",subcompanyname);
            json.put("departmentname",departmentname);
            json.put("lastname",lastname);
            json.put("mainrequestid",mainrequestid);
            json.put("wfrequestid",wfrequestid);

            json.put("ndjhxm",ndjhxm);
            json.put("ndjhys",ndjhys);
            json.put("ndjhsyed",ndjhsyed);
            json.put("qzjldwjezj",qzjldwjezj);
            json.put("zcldjljehj",zcldjljehj);
            ModelJson.put(id,json);
            DetailJson.put(id,copyJson(json));

        }
        log1.writeLog(Depjson.toJSONString());
        Depjson.put("DetailJson",DetailJson);
        return Depjson;
    }
    public static String getAdd(String d,String x,int len){
        String wsdj="0";
        if(d==null|| Util.null2String(d).trim().equals("")){
            d="0";
        }
        if(x==null|| Util.null2String(x).trim().equals("")){
            x="0";
        }
        try{
            BigDecimal allBig=new BigDecimal(d);
            BigDecimal newslBig=new BigDecimal( x);
            wsdj=allBig.add(newslBig).setScale(len,BigDecimal.ROUND_HALF_UP).toString();
        }catch(Exception e){

        }
        return wsdj;
    }
    /*
        获取部门所在的分部
     */
    public static String getSubByDep(String bm){
        RecordSet re=new RecordSet();
        String subcompanyid1="";
        String sql="select subcompanyid1 from hrmdepartment where id='"+bm+"'";
        re.execute(sql);
        while(re.next()){
            subcompanyid1= Util.null2String( re.getString("subcompanyid1")).trim();
        }
        return subcompanyid1;
    }
    public static JSONObject copyJson(JSONObject json){
        JSONObject newJson=new JSONObject();
        if(json==null||json.size()<=0){
            return newJson;
        }
        String str= JSONObject.toJSONString(json);
        if(str!=null){
            try{
                newJson= JSONObject.parseObject(str);
            }catch(Exception e){

            }
        }
        return newJson;
    }
    /*
    同步分部ID获取分部 名称
     */
    public static String getSubNameBySubid(String id){
        RecordSet re=new RecordSet();
        String subcompanyname="";
        String sql="SELECT subcompanyname FROM HrmSubCompany where id='"+id+"'";
        re.execute(sql);
        while(re.next()){
            subcompanyname= Util.null2String(re.getString("subcompanyname")).trim();
        }
        return subcompanyname;
    }
    /*
    check 判断是否存在 未变更数据
     */
    public  static boolean checkChangeWf(String requestid,String bgrequestid){
        bgrequestid= Util.null2String(bgrequestid).trim();
        if("".equals(Util.null2String(requestid).trim())){
            return false;
        }
        RecordSet re=new RecordSet();
        String sql=" select a.requestid from formtable_main_107 a,workflow_requestbase b where a.requestid=b.requestid and b.currentnodetype in (1,2) and a.yzjljllc='"+requestid+"'" +
                   " union all " +
                   " select a.requestid from formtable_main_108 a,workflow_requestbase b where a.requestid=b.requestid and b.currentnodetype in (1,2) and a.yzjljllc='"+requestid+"'";
        re.execute(sql);
        while(re.next()){
            String wfrequestid= Util.null2String("requestid").trim();
            if(wfrequestid.equals(bgrequestid)){
                continue;
            }
            return true;
        }
        return false;
    }
    /*
    获取部门名称
     */
    public static String getDepNameByid(String id){
        RecordSet re=new RecordSet();
        String departmentname="";
        String sql="select departmentname from HrmDepartment where id='"+id+"' ";
        re.execute(sql);
        while(re.next()){
            departmentname= Util.null2String(departmentname).trim();
        }
        return departmentname;
    }
    /*
        获取当前部门的顶级部门
     */
    public static String getTopDepBydepid(String depid){
        String topdepid="";
        RecordSet re=new RecordSet();
        String sql="select * from hrmdepartment  where id='"+depid+"'";
        re.execute(sql);
        if(re.next()){
            int supdepid= Util.getIntValue(re.getString("supdepid"),0);
            if(supdepid>0){
                topdepid=getTopDepBydepid(supdepid+"");
            }else{
                topdepid=depid+"";
            }
        }
        return topdepid;
    }
    public static String getUUid(){
        UUID uuid = UUID.randomUUID();
        String id = UUID.randomUUID().toString();
        return id;
    }
    /*
        获取制表日期
     */
    public static String getCreateDate(){
        String date="";
        try{
            SimpleDateFormat sim=new SimpleDateFormat("yyyy年MM月dd日");
            date=sim.format(new java.util.Date());

        }catch(Exception e){

        }
        return date;
    }
    public static void main(String[] arg){
            System.out.println(getCreateDate());
    }
}
